package com.lzb.newloan;

import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bqs.risk.df.android.BqsDF;
import com.bqs.risk.df.android.BqsParams;
import com.bqs.risk.df.android.OnBqsDFContactsListener;
import com.bqs.risk.df.android.OnBqsDFListener;
import com.lzb.newloan.bqs.Datas;
import com.lzb.newloan.bqs.Global;
import com.lzb.newloan.bqs.PermissionUtils;
import com.lzb.newloan.menu.ResideMenu;
import com.lzb.newloan.utils.ActivityList;
import com.lzb.newloan.utils.AlertDialog;
import com.lzb.newloan.utils.BaseActivity;
import com.lzb.newloan.utils.Config;
import com.lzb.newloan.utils.HttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;


public class IndexActivity extends BaseActivity implements OnClickListener, OnBqsDFListener {

    private LinearLayout layoutLeftMenu;
    private ResideMenu resideMenu;
    private ImageView index_img;
    private TextView index_txt;
    private ImageView person_img;
    private TextView person_txt, index_left_menu_txt_name;
    private ImageView more_img;
    private TextView more_txt;
    private android.app.AlertDialog phoneDialog;
    private boolean isExit = false;
    private TimerTask timeTask;
    private Timer timer = new Timer();
    private TextView tvrefere;
    private String userId, telphone = "0755-82330972";
    private TextView tel;
    private int rzstatus;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.index2);
        initView();

        Intent intert = getIntent();
        int id = intert.getIntExtra("id", 0);
        if (id == 0) {
            changeFragment(new HomeFragment());
            index_img.setImageResource(R.drawable.home_blue);
            index_txt.setTextColor(getResources().getColor(R.color.yellor));
            person_img.setImageResource(R.drawable.person_gray);
            person_txt.setTextColor(getResources().getColor(R.color.gray));
            more_img.setImageResource(R.drawable.more_gray);
            more_txt.setTextColor(getResources().getColor(R.color.gray));
        } else if (id == 1) {
            changeFragment(new PersonFragment());
            index_img.setImageResource(R.drawable.home_gray);
            index_txt.setTextColor(getResources().getColor(R.color.gray));
            person_img.setImageResource(R.drawable.person_blue);
            person_txt.setTextColor(getResources().getColor(R.color.yellor));
            more_img.setImageResource(R.drawable.more_gray);
            more_txt.setTextColor(getResources().getColor(R.color.gray));
        } else {
            changeFragment(new HomeFragment());
            index_img.setImageResource(R.drawable.home_blue);
            index_txt.setTextColor(getResources().getColor(R.color.yellor));
            person_img.setImageResource(R.drawable.person_gray);
            person_txt.setTextColor(getResources().getColor(R.color.gray));
            more_img.setImageResource(R.drawable.more_gray);
            more_txt.setTextColor(getResources().getColor(R.color.gray));
        }

        PermissionUtils.requestMultiPermissions(this, requestPermissions, mPermissionGrant);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

    }

    //获取6.0运行时权限列表，不采集gps权限：BqsDF.getRuntimePermissions(false);
    public String[] requestPermissions = BqsDF.getRuntimePermissions();


    /**
     * 授权结果，该回调不管权限是拒绝还是同意都会进入该回调方法
     */
    private PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant() {
        @Override
        public void onPermissionGranted(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults, String[] requestPermissions) {
            Global.authRuntimePermissions = true;
            /**
             * 因为在启动页进行运行时权限授权，所以要在授权结果回调中出发一次初始化
             */
            initBqsDFSDK();

        }
    };


    @Override
    protected void onResume() {
        super.onResume();

        /**
         * Global.authRuntimePermissions:用于判断运行时权限是否授权
         *
         * BqsDF.canInitBqsSDK()：用于控制不被频繁初始化。如果设备指纹采集成功了，app不被kill的情况下30分钟内不会重复提交设备信息
         *
         */
        if (Global.authRuntimePermissions && BqsDF.canInitBqsSDK()) {
            initBqsDFSDK();
        }
    }

    private void printLog(String log) {
        if (true) {
            System.out.println(log);
        }
    }

    protected void initBqsDFSDK() {
        //1、添加设备信息采集回调
        BqsDF.setOnBqsDFListener(IndexActivity.this);
        BqsDF.setOnBqsDFContactsListener(new OnBqsDFContactsListener() {
            @Override
            public void onGatherResult(boolean gatherStatus) {
                printLog("通讯录采集状态 gatherStatus=" + gatherStatus);
            }

            @Override
            public void onSuccess(String tokenKey) {
                printLog("通讯录采集成功");
            }

            @Override
            public void onFailure(String resultCode, String resultDesc) {
                printLog("通讯录采集失败 resultCode=" + resultCode + " resultDesc=" + resultDesc);
            }
        });
        //BqsDF.setOnBqsDFCallRecordListener(...);

        //2、配置初始化参数
        BqsParams params = new BqsParams();
        params.setPartnerId(Datas.PARTNET_ID);//商户编号
        params.setTestingEnv(false);//false是生产环境 true是测试环境
        params.setGatherGps(true);
        params.setGatherContact(true);
        params.setGatherCallRecord(true);

        //3、执行初始化
        BqsDF.initialize(this, params);
        //采集通讯录
        BqsDF.commitContactsAndCallRecords(true, true);
        BqsDF.commitLocation();
        //BqsDF.commitLocation(longitude, latitude);

        //4、提交tokenkey到贵公司服务器
        String tokenkey = BqsDF.getTokenKey();

        //注意：上传tokenkey时最好再停留几百毫秒的时间（给SDK预留上传设备信息的时间）
        new CountDownTimer(500, 500) {
            @Override
            public void onTick(long l) {
            }

            @Override
            public void onFinish() {
                submitTokenkey();
            }
        }.start();
    }

    //#mark - OnBqsDFListener
    //设备采集成功
    @Override
    public void onSuccess(String tokenKey) {
        //回调的tokenkey和通过BqsDF.getTokenKey()拿到的值都是一样的
        printLog("白骑士SDK采集设备信息成功 tokenkey=" + tokenKey);
    }

    //设备采集失败
    @Override
    public void onFailure(String resultCode, String resultDesc) {
        printLog("白骑士SDK采集设备信息失败 resultCode=" + resultCode + " resultDesc=" + resultDesc);
    }

    /**
     * 提交tokenkey到贵公司服务器
     */
    private void submitTokenkey() {
//        SharedPreferences sp = getSharedPreferences("config", 0x0000);
//        userId = sp.getString("userid", "");

        String tokenkey = BqsDF.getTokenKey();

        printLog("提交tokenkey:" + tokenkey);

//        Toast.makeText(this,"获取"+tokenkey,Toast.LENGTH_LONG).show();

        SharedPreferences sp = getSharedPreferences("config",
                MODE_PRIVATE);
        Editor editor = sp.edit();
        editor.putString("tokenkey", tokenkey);
        editor.commit();


    }


    private void initView() {
        resideMenu = new ResideMenu(this);
        resideMenu.setBackground(R.color.blue);
        resideMenu.attachToActivity(this);

        // resideMenu.setScaleValue(0.6f);
        // 禁止使用右侧菜单
        resideMenu.setDirectionDisable(ResideMenu.DIRECTION_RIGHT);
        resideMenu.setDirectionDisable(ResideMenu.DIRECTION_LEFT);
        LayoutInflater mInflater = LayoutInflater.from(this);
        layoutLeftMenu = resideMenu.getLayoutLeftMenu();

        View convertView = mInflater.inflate(R.layout.activity_index_left2,
                layoutLeftMenu);
        TextView tv_contact = (TextView) convertView
                .findViewById(R.id.tv_contact);
        tv_contact.setOnClickListener(this);
        convertView.findViewById(R.id.invite_rela).setOnClickListener(this);
        convertView.findViewById(R.id.linear_problem).setOnClickListener(this);


        tvrefere = (TextView) convertView.findViewById(R.id.tv_refere);
        tvrefere.setOnClickListener(this);

        convertView.findViewById(R.id.contact_rela).setOnClickListener(this);
        convertView.findViewById(R.id.linear_aboutus).setOnClickListener(this);
        convertView.findViewById(R.id.market_rela).setOnClickListener(this);
        resideMenu.setMenuListener(new ResideMenu.OnMenuListener() {
            @Override
            public void openMenu() {
            }

            @Override
            public void closeMenu() {
            }
        });

        LinearLayout index_home = (LinearLayout) findViewById(R.id.index_home);
        index_home.setOnClickListener(this);
        LinearLayout index_person = (LinearLayout) findViewById(R.id.index_person);
        index_person.setOnClickListener(this);
        LinearLayout index_more = (LinearLayout) findViewById(R.id.index_more);
        index_more.setOnClickListener(this);
        index_img = (ImageView) findViewById(R.id.index_img);
        index_txt = (TextView) findViewById(R.id.index_txt);
        person_img = (ImageView) findViewById(R.id.person_img);
        person_txt = (TextView) findViewById(R.id.person_txt);
        more_img = (ImageView) findViewById(R.id.more_img);
        more_txt = (TextView) findViewById(R.id.more_txt);
        index_left_menu_txt_name = (TextView) convertView.findViewById(R.id.index_left_menu_txt_name);
        SharedPreferences sp = getSharedPreferences("config", 0x0000);
        userId = sp.getString("userid", "");

        HttpUtils.doPostAsyn(Config.HOME_INIT + "&userid=" + userId, "", mHandler, Config.CODE_HOME_INIT);

        String phone = sp.getString("phone", "");
//		int rzstatus = sp.getInt("rzstatus", 0);
//		int invest_status = sp.getInt("invest_status", 0);

        index_left_menu_txt_name.setText(phone);
    }

    public void changeFragment(Fragment targetFragment) {
        resideMenu.clearIgnoredViewList();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.index_fragment, targetFragment, "fragment")
                .setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
                .commit();
    }

    public ResideMenu getResideMenu() {
        return resideMenu;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.market_rela://贷款超市
                Intent intent2 = new Intent(IndexActivity.this,
                        MoreMarketActivity.class);
                startActivity(intent2);
                break;
            case R.id.index_home:
                changeFragment(new HomeFragment());
                index_img.setImageResource(R.drawable.home_blue);
                index_txt.setTextColor(getResources().getColor(R.color.yellor));
                person_img.setImageResource(R.drawable.person_gray);
                person_txt.setTextColor(getResources().getColor(R.color.gray));
                more_img.setImageResource(R.drawable.more_gray);
                more_txt.setTextColor(getResources().getColor(R.color.gray));
                break;
            case R.id.index_person:
                changeFragment(new PersonFragment());
                index_img.setImageResource(R.drawable.home_gray);
                index_txt.setTextColor(getResources().getColor(R.color.gray));
                person_img.setImageResource(R.drawable.person_blue);
                person_txt.setTextColor(getResources().getColor(R.color.yellor));
                more_img.setImageResource(R.drawable.more_gray);
                more_txt.setTextColor(getResources().getColor(R.color.gray));
                break;
            case R.id.index_more:
//                resideMenu.openMenu(ResideMenu.DIRECTION_LEFT);
                changeFragment(new MoreFragment());
                index_img.setImageResource(R.drawable.home_gray);
                index_txt.setTextColor(getResources().getColor(R.color.gray));
                person_img.setImageResource(R.drawable.person_gray);
                person_txt.setTextColor(getResources().getColor(R.color.gray));
                more_img.setImageResource(R.drawable.more_blue);
                more_txt.setTextColor(getResources().getColor(R.color.yellor));


                break;
            case R.id.contact_rela://
                this.phoneDialog = new android.app.AlertDialog.Builder(this)
                        .create();
                LayoutInflater lay = LayoutInflater
                        .from(((Context) IndexActivity.this));
                final View inflate = lay.inflate(R.layout.layout_dialog2,
                        (ViewGroup) null);
                inflate.findViewById(R.id.cancle).setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        IndexActivity.this.phoneDialog.dismiss();
                    }
                });
                tel = (TextView) inflate.findViewById(R.id.tel);

                final TextView textView = (TextView) inflate
                        .findViewById(R.id.dialog_ok);
                ((TextView) inflate.findViewById(R.id.dialog_cancle))
                        .setOnClickListener((View.OnClickListener) new View.OnClickListener() {
                            public void onClick(final View view) {
                                IndexActivity.this.phoneDialog.dismiss();
                            }
                        });
                inflate.findViewById(R.id.wx_problem).setOnClickListener(
                        new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                // 打开微信
                                IndexActivity.this.phoneDialog.dismiss();
                                try {
                                    Intent intent = new Intent(Intent.ACTION_MAIN);
                                    ComponentName cmp = new ComponentName(
                                            "com.tencent.mm",
                                            "com.tencent.mm.ui.LauncherUI");
                                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    intent.setComponent(cmp);
                                    startActivity(intent);
                                } catch (ActivityNotFoundException e) {
                                    Toast.makeText(IndexActivity.this,
                                            "检查到您手机没有安装微信，请安装后使用该功能",
                                            Toast.LENGTH_LONG).show();
                                }

                            }
                        });
                inflate.findViewById(R.id.qq_problem).setOnClickListener(
                        new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                // 打开扣扣进行客服沟通
                                IndexActivity.this.phoneDialog.dismiss();
                                try {
                                    String url = "mqqwpa://im/chat?chat_type=wpa&uin=3387316533";
                                    startActivity(new Intent(Intent.ACTION_VIEW,
                                            Uri.parse(url)));
                                } catch (ActivityNotFoundException e) {
                                    Toast.makeText(IndexActivity.this,
                                            "检查到您手机没有安装QQ，请安装后使用该功能",
                                            Toast.LENGTH_LONG).show();
                                }
                            }
                        });
                inflate.findViewById(R.id.tel_problem).setOnClickListener(
                        new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                // 拨打电话
                                IndexActivity.this.phoneDialog.dismiss();
                                IndexActivity.this.startActivity(new Intent(
                                        Intent.ACTION_DIAL, Uri
                                        .parse("tel:4006899830")));

                            }
                        });
                textView.setOnClickListener((View.OnClickListener) new View.OnClickListener() {
                    public void onClick(final View view) {
                    }
                });
                this.phoneDialog.show();
                this.phoneDialog.setCanceledOnTouchOutside(false);
                this.phoneDialog.setContentView(inflate);

//                HttpUtils.doPostAsyn(Config.PHONE_CORD, "",mHandler, Config.CODE_PHONE);
                break;
            case R.id.invite_rela:
                startActivity(new Intent(getApplicationContext(),
                        InviteActivity.class));

                break;
            case R.id.linear_aboutus:
                Intent intents = new Intent(IndexActivity.this, ProblemActivity.class);
                intents.putExtra("title", "关于我们");
                intents.putExtra("url", "http://wx.lvzbao.com/wx/main/SDAboutus.html");
                startActivity(intents);
                break;
            case R.id.linear_problem:
                Intent intent = new Intent(IndexActivity.this, ProblemActivity.class);
                intent.putExtra("title", "常见问题");
                intent.putExtra("url", Config.COMMON_PROBLEM);
                startActivity(intent);
                break;
            case R.id.tv_refere:
//
                if (rzstatus != 1) {
                    new AlertDialog(IndexActivity.this).builder().setMsg("请先绑定银行卡")
                            .setNegativeButton("确定", new OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                    startActivity(new Intent(IndexActivity.this, BindCard2Activity.class));

                                }
                            }).show();
                } else {
                    SharedPreferences sp = getSharedPreferences("config", 0x0000);
                    String userId = sp.getString("userid", "");
                    HttpUtils.doPostAsyn(Config.CHECKINVESTOR + "&userid=" + userId, "", mHandler,
                            Config.CODE_CHECKINVESTOR);
                }

                break;
            default:
                break;
        }
    }


    private Handler mHandler = new Handler() {

        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case Config.CODE_PHONE:
                    try {
                        JSONObject response = new JSONObject(msg.obj.toString());
                        telphone = response.optString("phone");
                        tel.setText("Tel联系：" + telphone);
                    } catch (JSONException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                    break;
                case Config.CODE_HOME_INIT:
                    try {
                        JSONObject response = new JSONObject(msg.obj.toString());
                        rzstatus = Integer.parseInt(response
                                .getString("rzstatus"));
                        int invest_status = Integer.parseInt(response
                                .getString("invest_status"));
                        if (rzstatus == 1) {
                            if (invest_status == 1) {
                                tvrefere.setText("切换到投资");
                            } else {
                                tvrefere.setText("申请投资人");
                            }

                        } else {
                            tvrefere.setText("申请投资人");
                        }

                    } catch (JSONException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } catch (NumberFormatException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    break;
                case Config.CODE_CHECKINVESTOR:
                    try {
                        String result = msg.obj.toString();
                        JSONObject response = new JSONObject(result);
//                        if (rzstatus == 1) {
                        int error = response.getInt("error");
                        String msgs = response.getString("msg");
                        if (error == -1) {//已成为投资人

                            startActivity(new Intent(IndexActivity.this,
                                    InvestPersonActivity.class));

                        } else if (error == 0) {//申请投资人

                            startActivity(new Intent(IndexActivity.this,
                                    ApplayInvesterActivity.class));
                        } else {
                            new AlertDialog(IndexActivity.this)
                                    .builder()
                                    .setMsg(msgs)
                                    .setNegativeButton("确定",
                                            new OnClickListener() {
                                                @Override
                                                public void onClick(View v) {

                                                }
                                            }).show();
                        }
                    } catch (NumberFormatException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    break;
                case Config.CODE_URL_ERROR:
                    Toast.makeText(IndexActivity.this, "url错误",
                            Toast.LENGTH_SHORT).show();
                    break;
                case Config.CODE_NET_ERROR:
                    Toast.makeText(IndexActivity.this, "网络错误",
                            Toast.LENGTH_SHORT).show();
                    // if (time!=null) {
                    // time.cancel();
                    // }
                    break;

                default:
                    break;
            }
        }

    };

    // 监听返回键是否退出
    @Override
    public void onBackPressed() {
        if (isExit) {
            ActivityList.tuichu();
            this.finish();
            System.exit(0);
        } else {
            isExit = true;
            Toast.makeText(this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
            timeTask = new TimerTask() {

                @Override
                public void run() {
                    isExit = false;
                }
            };
            timer.schedule(timeTask, 3000);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return resideMenu.dispatchTouchEvent(ev);
    }

    @Override
    public void processMessage(Message message) {
        // TODO Auto-generated method stub

    }
}
